//
//  JHChatViewController.m
//  JHChat
//
//  Created by JiaHao on 2/22/15.
//  Copyright (c) 2015 JiaHao. All rights reserved.
//

#import "JHChatViewController.h"
#import "HPGrowingTextView.h"
#import "AGEmojiKeyBoardView.h"
#import <AVFoundation/AVFoundation.h>
#import "JHToolView.h"

#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
static XMPPJID *currentChatBuddyJid = nil;

@interface JHChatViewController ()<AVAudioPlayerDelegate,HPGrowingTextViewDelegate,UITextViewDelegate,AGEmojiKeyboardViewDataSource,AGEmojiKeyboardViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *chatTableview;
@property (weak, nonatomic) IBOutlet UIView *toolView;
@property (strong, nonatomic) UIImageView *sendBackView;
@property (strong, nonatomic) UIImageView *sendBackGround;
@property (strong, nonatomic) AGEmojiKeyboardView *emojiKeyBoardView;
@property (strong, nonatomic) HPGrowingTextView *messageTextView;

@property (strong, nonatomic) UIButton *recordingChangeButton;
@property (strong, nonatomic) UIButton *sendExpressButton;
@property (strong, nonatomic) UIButton *sendItButton;
@property (strong, nonatomic) UIButton *sendPicButton;
@property (strong, nonatomic) UIButton *speakingButton;
@property (nonatomic) CGFloat lastSendViewHeight;

@end

@implementation JHChatViewController


#pragma mark 键盘即将显示
- (void)keyBoardWillShow:(NSNotification *)note{
    CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat ty = - rect.size.height;
    [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, ty);
    }];
}
#pragma mark 键盘即将退出
- (void)keyBoardWillHide:(NSNotification *)note{
    [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark - 代理方法 - 拉关闭键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.currentJid.user;
    self.chatTableview.tableFooterView = [UIView new];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
   // [self cofigToolView];
    [self addEmojiKeyboard];


    JHToolView *tool = [[JHToolView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 44, SCREEN_WIDTH, 44)];
    [self.view addSubview:tool];
}

-(void)cofigToolView
{
    
    //键盘说话
    self.recordingChangeButton = [[UIButton alloc]initWithFrame:CGRectMake(8, 8, 28, 28)];
    [self.recordingChangeButton setBackgroundImage:[UIImage imageNamed:@"chat_voice_icon.png"] forState:UIControlStateNormal];
    [self.recordingChangeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //[self.recordingChangeButton addTarget:self action:@selector(recordingPressed) forControlEvents:UIControlEventTouchDown];
    [self.toolView addSubview:self.recordingChangeButton];
  
    
    //图片选择按钮
    self.sendPicButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 30, 8, 28, 28)];
    [self.sendPicButton setBackgroundImage:[UIImage imageNamed:@"chat_add_icon.png"] forState:UIControlStateNormal];
    //[self.sendPicButton addTarget:self action:@selector(chooseAPicture) forControlEvents:UIControlEventTouchDown];
    [self.toolView addSubview:self.sendPicButton];
    
    
    //调出表情键盘按钮
    self.sendExpressButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 65, 8, 28, 28)];
    [self.sendExpressButton setBackgroundImage:[UIImage imageNamed:@"chat_express_icon.png"] forState:UIControlStateNormal];
    [self.sendExpressButton addTarget:self action:@selector(chooseAExpression) forControlEvents:UIControlEventTouchDown];
    [self.toolView addSubview:self.sendExpressButton];
    
    //语音按钮初始状态
    self.speakingButton= [[UIButton alloc]initWithFrame:CGRectMake(45, 9, SCREEN_WIDTH-110, 30)];
    [self.speakingButton setBackgroundColor:[UIColor clearColor]];
    [self.speakingButton setTitle:@"按住说话" forState:UIControlStateNormal];
    [self.speakingButton setTitle:@"松开录制完成" forState:UIControlStateHighlighted];
    [self.speakingButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.speakingButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    self.speakingButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    //[self.speakingButton addTarget:self action:@selector(touchDown) forControlEvents:UIControlEventTouchDown];
    //[self.speakingButton addTarget:self action:@selector(touchUp) forControlEvents:UIControlEventTouchUpInside];
    [self.toolView addSubview:self.speakingButton];
    self.speakingButton.hidden = YES;
    
    //可扩展textView背景
    self.messageTextView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(45, 7, SCREEN_WIDTH-120, 30)];
    self.messageTextView.isScrollable = NO;
    self.messageTextView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    
    self.messageTextView.maxNumberOfLines = 5;
    self.messageTextView.minNumberOfLines = 1;
    
    self.messageTextView.font = [UIFont systemFontOfSize:15.0f];
    self.messageTextView.delegate = self;
    self.messageTextView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    self.messageTextView.backgroundColor = [UIColor clearColor];
    self.messageTextView.returnKeyType = UIReturnKeySend;
    
    UIImage * backView = [UIImage imageNamed:@"chat_inputbox_bg.png"];
    self.sendBackView = [[UIImageView alloc] initWithImage:[backView stretchableImageWithLeftCapWidth:floorf(backView.size.width/2) topCapHeight:floorf(backView.size.height/2)]];
    [self.sendBackView setFrame:CGRectMake(40, 7, SCREEN_WIDTH - 110, self.toolView.frame.size.height-14)];
    
    [self.toolView addSubview:self.sendBackView];
    [self.toolView sendSubviewToBack:self.sendBackView];
    
    //sendview背景添加
    UIImage * backGround = [UIImage imageNamed:@"chat_image_bg"];
    self.sendBackGround = [[UIImageView alloc] initWithImage:[backGround stretchableImageWithLeftCapWidth:floorf(backGround.size.width/2) topCapHeight:floorf(backGround.size.height/2)]];
    [self.sendBackGround setFrame:CGRectMake(0, 0, self.toolView.frame.size.width, self.toolView.frame.size.height)];
    [self.toolView addSubview:self.sendBackGround];
    [self.toolView sendSubviewToBack:self.sendBackGround];
    
    [self.toolView addSubview:self.messageTextView];
}

-(void)addEmojiKeyboard{
    self.emojiKeyBoardView = [[AGEmojiKeyboardView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 216) dataSource:self];
    self.emojiKeyBoardView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    self.emojiKeyBoardView.delegate = self;
}

#pragma mark - 表情键盘
- (void)chooseAExpression {
    [self.messageTextView resignFirstResponder];
    if (self.messageTextView.internalTextView.inputView == self.emojiKeyBoardView) {
        self.messageTextView.internalTextView.inputView = nil;
    }else{
        self.messageTextView.internalTextView.inputView = self.emojiKeyBoardView;
    }
    [self.messageTextView becomeFirstResponder];
}

-(void)emojiKeyBoardView:(AGEmojiKeyboardView *)emojiKeyBoardView didUseEmoji:(NSString *)emoji{
    self.messageTextView.text = [self.messageTextView.text stringByAppendingString:emoji];
}

//退格键
-(void)emojiKeyBoardViewDidPressBackSpace:(AGEmojiKeyboardView *)emojiKeyBoardView{
    if (![self.messageTextView.text isEqualToString:@""]) {
        self.messageTextView.text = [self.messageTextView.text substringToIndex:self.messageTextView.text.length -1];
    }
}
//自定义的segment键
- (UIColor *)randomColor {
    return [UIColor colorWithRed:drand48()
                           green:drand48()
                            blue:drand48()
                           alpha:drand48()];
}
- (UIImage *)randomImage {
    CGSize size = CGSizeMake(30, 10);
    UIGraphicsBeginImageContextWithOptions(size , NO, 0);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIColor *fillColor = [self randomColor];
    CGContextSetFillColorWithColor(context, [fillColor CGColor]);
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    CGContextFillRect(context, rect);
    
    fillColor = [self randomColor];
    CGContextSetFillColorWithColor(context, [fillColor CGColor]);
    CGFloat xxx = 3;
    rect = CGRectMake(xxx, xxx, size.width - 2 * xxx, size.height - 2 * xxx);
    CGContextFillRect(context, rect);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
//选中segment图片
-(UIImage *)emojiKeyboardView:(AGEmojiKeyboardView *)emojiKeyboardView imageForSelectedCategory:(AGEmojiKeyboardViewCategoryImage)category{
    UIImage *img = [self randomImage];
    [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    return img;
}
//未选中segment图片
-(UIImage *)emojiKeyboardView:(AGEmojiKeyboardView *)emojiKeyboardView imageForNonSelectedCategory:(AGEmojiKeyboardViewCategoryImage)category{
    UIImage *img = [self randomImage];
    [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    return img;
}
//删除按钮图片
-(UIImage *)backSpaceButtonImageForEmojiKeyboardView:(AGEmojiKeyboardView *)emojiKeyboardView{
    UIImage *img = [UIImage imageNamed:@"del_emoji_normal.png"];
    [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    return img;
}

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    
    CGRect r = self.toolView.frame;
    r.size.height -= diff;
    r.origin.y += diff;
    self.toolView.frame = r;
    CGRect t = self.chatTableview.frame;
    t.size.height += diff;
    self.chatTableview.frame = t;
    
    [self.sendBackGround setFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.toolView.frame.size.height)];
    [self.sendBackView setFrame:CGRectMake(40, 7, SCREEN_WIDTH - 110, self.toolView.frame.size.height-14)];
    
    self.lastSendViewHeight = self.toolView.frame.size.height;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
